package cn.lizhangqu.kb.service;

import android.util.Log;

import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;
import org.litepal.crud.DataSupport;

import java.util.List;

import cn.lizhangqu.kb.model.Score;

/**
 * Created by 柯尊诚 on 2015/11/3.
 * kzc
 */
public class ScoreService {

    private static volatile ScoreService scoreService;
    private ScoreService(){};
    public static ScoreService getScoreService() {
        if (scoreService == null) {
            synchronized (ScoreService.class) {
                if (scoreService == null)
                    scoreService = new ScoreService();
            }
        }
        return scoreService;
    }

    /**
     * 保存一门课成绩信息
     */
    public boolean save(Score score) {
        return score.save();
    }

    /**
     * 查询所有成绩信息
     */
    public List<Score> findAll() {
        return DataSupport.findAll(Score.class);
    }


    /**
     * 解析成绩
     * @param content 带标签的数据
     * @return
     */
    public String parseScore(String content) {
        Log.d("kzc", content);
        Document doc = Jsoup.parse(content);

        Elements elements = doc.select("table#Datagrid1");//提取指定标签数据
        Element element = elements.get(0).child(0);
        element.child(0).remove();//去除头部

        //获取行数
        int rowNum = element.childNodeSize();
//        Log.d("xxnum","==========>"+rowNum);
        for (int i = 0; i < rowNum - 1; i++) {
            Element row = element.child(i);
            getScoreData(row);
        }
        return element.toString();
    }

    /**
     * 获取查询成绩所需的表单信息
     * @param content 带标签的数据
     * @return 表单信息
     */
    public String parseScoreCode(String content) {
        Document doc = Jsoup.parse(content);
        Element elements = doc.getElementsByAttributeValue("name","__VIEWSTATE").first();
        return elements.val();
    }

    /**
     * 获取单行成绩值，并保存
     * @param row 一行
     * @return 成绩对象
     */
    public Score getScoreData(Element row) {
        //获得一行的列数
        int columnNum = row.childNodeSize();
        Log.d("xxnum", "==========>" + columnNum);

        String toYear = row.child(0).text();
        String[] yearData = toYear.split("-");

        Score score = new Score();
        score.setStartYear(yearData[0]);
        score.setEndYear(yearData[1]);
        score.setSemester(row.child(1).text());
        score.setCourseCode(row.child(2).text());
        score.setCourseName(row.child(3).text());
        score.setCourseClass(row.child(4).text());
        //中间有个空的
        score.setCredits(row.child(6).text());//学分
        score.setGradePoint(row.child(7).text());
        score.setScoreValue(row.child(8).text());
        //后面信息不重要
        //.....
        //保存对象
        save(score);
        return score;
    }

}
